<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="评论类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择 微圈  课程  商品" clearable>
          <el-option
            v-for="dict in dict.type.sy_comment"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回复时间" prop="replytime">
        <el-date-picker clearable
          v-model="queryParams.replytime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择回复时间戳">
        </el-date-picker>
      </el-form-item>
  <!--    <el-form-item label="父节点评论" prop="pid">
        <el-input
          v-model="queryParams.pid"
          placeholder="请输入父节点评论"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="cerateBy">
        <el-input
          v-model="queryParams.cerateBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="评论区ID" prop="commentId">
        <el-input
          v-model="queryParams.commentId"
          placeholder="请输入评论区ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['comment:comment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="commentList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="评论类型" width="80" align="center">
		<template slot-scope="scope">
		   <dict-tag :options="dict.type.sy_comment" :value="scope.row.type"/>
		 </template>
      </el-table-column>
	  <el-table-column label="ID"width="100" align="center" prop="id" />
      <el-table-column label="回复人的UID"width="100" align="center" prop="userId" />
      <el-table-column label="回复时间戳" align="center" prop="replytime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.replytime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
	  <el-table-column label="评论区ID" width="100" align="center" prop="commentId" />
      <el-table-column label="回复内容"  align="center" prop="content" />
      <!-- <el-table-column label="父节点评论" align="center" prop="pid" /> -->
      <!-- <el-table-column label="创建人" align="center" prop="cerateBy" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['comment:comment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['comment:comment:add']"
          >新增</el-button>
		  <el-button
		    size="mini"
		    type="text"
		    icon="el-icon-view"
		    @click="handleView(scope.row)"
		    v-hasPermi="['comment:comment:lists']"
		  >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['comment:comment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改评论对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="1 微圈 2 课程  3 商品" prop="type">
          <el-select v-model="form.type" placeholder="请选择1 微圈 2 课程  3 商品">
            <el-option
              v-for="dict in dict.type.sy_comment"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
		<el-form-item label="回复人ID">
		   <el-input v-model="form.userId" placeholder="请输入用户ID" />
		</el-form-item>
        <el-form-item label="回复时间戳" prop="replytime">
          <el-date-picker clearable
            v-model="form.replytime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择回复时间戳">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回复内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="父节点评论" prop="pid">
          <treeselect v-model="form.pid" :options="commentOptions" :normalizer="normalizer" placeholder="请选择父节点评论" />
        </el-form-item>
        <el-form-item label="创建人" prop="cerateBy">
          <el-input v-model="form.cerateBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="评论区ID" prop="commentId">
          <el-input v-model="form.commentId" placeholder="请输入评论区ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
	
	<el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
	  <el-descriptions class="margin-top" :column="3" :size="size" border>
	    <!-- Top Section -->
	    <el-descriptions-item label="评论类型" prop="type">
			<dict-tag
			:options="dict.type.sy_comment"
			:value="form.type"
			/>
		</el-descriptions-item>
	    <el-descriptions-item label="回复时间">{{ form.replytime }}</el-descriptions-item>
	    <el-descriptions-item label="评论区ID">{{ form.commentId }}</el-descriptions-item>
	    <el-descriptions-item label="回复内容">{{form.content}} </el-descriptions-item>
	  </el-descriptions>
	  <br />
	  <!-- Bottom Section -->
	 <el-descriptions class="margin-top" :column="2" :size="size" border>
	       <el-descriptions-item label="用户ID">{{ form.userId }}</el-descriptions-item>
	       <el-descriptions-item label="用户名称">{{ form.syAppUsers.username }}</el-descriptions-item>
	       <el-descriptions-item label="用户邮箱">{{ form.syAppUsers.email }}</el-descriptions-item>
	       <el-descriptions-item label="电话号码">{{ form.syAppUsers.phone }}</el-descriptions-item>
	     </el-descriptions>
	     <br />
	 
	     <!-- 课程信息部分 -->
	     <el-descriptions class="margin-top" :column="2" :size="size" v-if="form.type == '2'" border>
	       <el-descriptions-item label="评论区id">{{ form.commentId }}</el-descriptions-item>
	       <el-descriptions-item label="课程名称">{{ form.syCourse.courseName }}</el-descriptions-item>
	       <el-descriptions-item label="作者">{{ form.syCourse.username }}</el-descriptions-item>
	       <el-descriptions-item label="课程简介">{{ form.syCourse.courseIntro }}</el-descriptions-item>
	       <el-descriptions-item label="缩略图">
	         <image-preview v-if="form.syCourse.thum" :src="form.syCourse.thum" :width="200" :height="200"/>
	       </el-descriptions-item>
	     </el-descriptions>
	 
	     <!-- 微圈信息部分 -->
	     <el-descriptions class="margin-top" :column="2" :size="size" v-if="form.type == '1'" border>
	       <el-descriptions-item label="评论区id">{{ form.commentId }}</el-descriptions-item>
	       <el-descriptions-item label="微圈标题">{{ form.syMicrocircle.articleTitle }}</el-descriptions-item>
	       <el-descriptions-item label="关键词">{{ form.syMicrocircle.articleKeywords }}</el-descriptions-item>
		   <el-descriptions-item label="内容">{{ form.syMicrocircle.articleContent }}</el-descriptions-item>
		    <el-descriptions-item label="文章图">
		      <image-preview v-if="form.syMicrocircle.articleUrls" :src="form.syMicrocircle.articleUrls" :width="200" :height="200"/>
		    </el-descriptions-item>
	     </el-descriptions>
	 
	     <!-- 商品信息部分 -->
	     <el-descriptions class="margin-top" :column="2" :size="size" v-if="form.type == '3'" border>
	       <el-descriptions-item label="评论区id">{{ form.commentId }}</el-descriptions-item>
	       <el-descriptions-item label="商品名称">{{ form.syProduct.publicName }}</el-descriptions-item>
	       <el-descriptions-item label="商品描述">{{ form.syProduct.content }}</el-descriptions-item>
	       <el-descriptions-item label="商品图片">
	         <image-preview v-if="form.syProduct.productImageId" :src="form.syProduct.productImageId" :width="200" :height="200"/>
	       </el-descriptions-item>
	     </el-descriptions>

	  <div slot="footer" class="dialog-footer">
	    <el-button @click="viewClose">关 闭</el-button>
	  </div>
	</el-dialog>
  </div>
</template>

<script>
import { listComment, getComment, delComment, addComment, updateComment , getComments, getCommentP, getCommentM } from "@/api/comment/comment.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Comment",
  dicts: ['sy_comment'],
  components: {
    Treeselect
  },
 data() {
   return {
     size: 'medium',
     viewOpen: false,
     loading: true,
     showSearch: true,
     commentList: [],
     commentOptions: [],
     title: "",
     open: false,
     isExpandAll: true,
     refreshTable: true,
     queryParams: {
       type: null,
       userId: null,
       replytime: null,
       content: null,
       pid: null,
       cerateBy: null, // 注意拼写错误，应该是 createBy
       commentId: null
     },
     form: {
       id: null,
             type: null,
             userId: null,
             replytime: null,
             content: null,
             pid: null,
             createBy: null, // 修正拼写错误
             updateBy: null,
             createTime: null,
             updateTime: null,
             commentId: null,
             username: null,
             syAppUsers: {
               username: null,
               email: null,
               phone: null,
             },
             syCourse: {
               courseName: null,
               username: null,
               courseIntro: null,
               thum: null,
             },
             syProduct: {
               publicName: null,
               content: null,
               productImageId: null,
             },
             syMicrocircle: {
               articleKeywords: null,
               articleUrls: null,
               articleTitle: null,
			   articleContent: null,
			   
             }
     },
     rules: {
       type: [
         { required: true, message: "1 微圈 2 课程  3 商品不能为空", trigger: "change" }
       ],
       replytime: [
         { required: true, message: "回复时间戳不能为空", trigger: "blur" }
       ],
       content: [
         { required: true, message: "回复内容不能为空", trigger: "blur" }
       ],
     }
   };
 },
  created() {
    this.getList();
  },
  
  methods: {
    /** 查询评论列表 */
    getList() {
      this.loading = true;
      listComment(this.queryParams).then(response => {
        this.commentList = this.handleTree(response.data, "id", "pid");
        this.loading = false;
      });
    },
	
    /** 转换评论数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.commentId,
        children: node.children
      };
    },
	/** 查询评论下拉树结构 */
    getTreeselect() {
      listComment().then(response => {
        this.commentOptions = [];
        const data = { id: 0, commentId: '商品分类', children: [] };
        data.children = this.handleTree(response.data, "id", "pid");
        this.commentOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
	viewClose(){
	  this.viewOpen = false;
	},
    // 表单重置
   reset() {
     this.form = {
       id: null,
       type: null,
       userId: null,
       replytime: null,
       content: null,
       pid: null,
       cerateBy: null, // 注意拼写错误，应该是 createBy
       updateBy: null,
       createTime: null,
       updateTime: null,
       commentId: null,
       username: null,
       syAppUsers: {
         username: null,
         email: null,
         phone: null,
       },
       syCourse: {
         courseName: null,
         username: null,
         courseIntro: null,
         thum: null,
       },
       syProduct: {
       		 publicName: null,
       		 content: null,
       		 productImageId: null,
			 soldNum:null,
       },
       syMicrocircle: {
       		articleKeywords: null,
       		articleUrls: null,
       		articleTitle: null,
       		articleContent: null,
       		
       }
     };
     this.resetForm("form");
   },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
	
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.pid = row.id;
      } else {
        this.form.pid = 0;
      }
      this.open = true;
      this.title = "添加评论";
    },
    //修改
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.pid = row.pid;
      }
      getComment(row.id).then(response => {
        if (response.code === 200) { // 假设后端成功响应码为200
          this.form = { ...this.form, ...response.data };
          if (!this.form.syAppUsers) {
            this.form.syAppUsers = {
              username: null,
              email: null,
              phone: null,
            };
          }
          if (!this.form.syCourse) {
            this.form.syCourse = {
              courseName: null,
              username: null,
              courseIntro: null,
              thum: null,
            };
          }
		  if (!this.form.syProduct) {
		    this.form.syProduct = {
		     publicName: null,
		     content: null,
		     productImageId: null,
		    };
		  }
		  if (!this.form.syMicrocircle) {
		    this.form.syMicrocircle = {
		     publicName: null,
		     content: null,
		     productImageId: null,
		    };
		  }
          this.open = true;
          this.title = "修改评论";
        } else {
          this.$modal.msgError(response.message || "获取评论信息失败");
        }
      }).catch(error => {
        console.error("获取评论信息失败:", error);
        this.$modal.msgError("获取评论信息失败，请稍后再试");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
	//   getComment(row.id).then(response => {
	//     this.form = response.data;
	//     this.open = true;
	//     this.title = "修改评论";
	//   });
	// },
	handleView(row) {
	  console.log('Row:', row);
	  const orderId = row.id;
	
	  if (row.type == '2') {
	    getComments(orderId).then(response => {
	      this.assignForm(response.data);
	      this.title = "查看";
	      this.viewOpen = true; // 打开查看对话框
	    }).catch(error => {
	      console.error("获取评论信息失败:", error);
	      this.$modal.msgError("获取评论信息失败，请稍后再试");
	    });
	  } else if (row.type == '3') {
	    getCommentP(orderId).then(response => {
	      // 确保 response.data 是一个对象而不是数组
	      if (Array.isArray(response.data) && response.data.length > 0) {
	        this.assignForm(response.data[0]);
	      } else {
	        this.assignForm(response.data || {});
	      }
	      this.title = "查看";
	      this.viewOpen = true; // 打开查看对话框
	    }).catch(error => {
	      console.error("获取评论信息失败:", error);
	      this.$modal.msgError("获取评论信息失败，请稍后再试");
	    });
	  }else if (row.type == '1') {
	    getCommentM(orderId).then(response => {
	      // 确保 response.data 是一个对象而不是数组
	      if (Array.isArray(response.data) && response.data.length > 0) {
	        this.assignForm(response.data[0]);
	      } else {
	        this.assignForm(response.data || {});
	      }
	      this.title = "查看";
	      this.viewOpen = true; // 打开查看对话框
	    }).catch(error => {
	      console.error("获取评论信息失败:", error);
	      this.$modal.msgError("获取评论信息失败，请稍后再试");
	    });
	  }
	},
    assignForm(data) {
      this.form = { ...this.form, ...data };
      if (!this.form.syAppUsers) {
        this.form.syAppUsers = {
         username: null,
         email: null,
         phone: null,
        };
      }
      if (!this.form.syCourse) {
        this.form.syCourse = {
          courseName: null,
          username: null,
          courseIntro: null,
          thum: null,
        };
      }
      if (!this.form.syProduct) {
        this.form.syProduct = {
          publicName: null,
          content: null,
          productImageId: null,
        };
      }
      if (!this.form.syMicrocircle) {
        this.form.syMicrocircle = {
         articleKeywords: null,
         articleUrls: null,
         articleTitle: null,
         articleContent: null,
        };
      }
    },
  
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateComment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addComment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除评论编号为"' + row.id + '"的数据项？').then(function() {
        return delComment(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
